var appPath = getAppPath();

$(function(){
	initJspGrid();
});

// 图片列表初始化
function initJspGrid(){
	
	$('#graphGrid').datagrid({
	    url:appPath + "/itbGraph/getGraphList.action",
	    height:'full',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam(),
	    singleSelect:false,
		checkbox:false,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
	        {field:'thumb',title:'缩略图',width:85,align:'center',sortable:false,
	        	formatter:function(thumb, rowData, rowIndex){
	        		var retUrl = '';
	        		if (rowData.thumb) {
	        			retUrl = '<a href="' + rowData.thumb + '" target="_blank">'
	        				+ '<div style="display:table;text-align:center;height:120px;width:100%">'
	        				+ '<span style="display:table-cell;vertical-align:middle">'
	        				+ '<img src="' + rowData.thumb.replace('oss-cn-hangzhou.aliyuncs.com','img-cn-hangzhou.aliyuncs.com') + '@110h_128w_1l.png'
	        				+ '" style="display:inline;max-height:110px;max-width:128px"><span></div></a>';
	        		}
	        		return retUrl;
	        	}},
			{field:'editGraph',title:'编辑',width:30,align:'center',sortable:false,
				formatter:function(value,rowData,rowIndex){
					if (!rowData.graph_id){
						return "";
					} else {
						return "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑图形' onClick='showEditInfo("+rowData.graph_id+")'/></a>";
					}
				}
			},
	        {field:'graph_id',title:'图形ID',width:40,align:'center',sortable:true},
	        {field:'graph_name',title:'图形名称',width:142,align:'center',sortable:true},
	        {field:'graph_type',title:'图形类别',width:68,align:'center',sortable:true,
	        	formatter:function(value,rowData,rowIndex){
	        		var str = "未知分类 "+value;
//	        		if (value == 0){
//	        			str = "实心";
//	        		} else if (value == 1){
//	        			str = "数字";
//	        		} else if (value == 2){
//	        			str = "简单图形";
//	        		}
	        		if(rowData.type_name){
	        			str = rowData.type_name;
	        		}
	        		return str;
	        	}
	        }, 
	        {field:'create_time',title:'创建时间',width:80,align:'center',sortable:true}, 
	        {field:'update_time',title:'修改时间',width:80,align:'center',sortable:true}
	    ]],
	    hideColumn:['user_type'],
	    pagination:true,
		rownumbers:true,
		toolbar:[{
			text:'添加图形',
			iconCls:'icon-add',
			handler:function(){
				showAddInfo();
			}
		},{
			text:'刷新缩略图',
			iconCls:'icon-reload',
			handler:function(){
				refreshThumb();
			}
		},{
			text:'删除图形',
			iconCls:'icon-cancel',
			handler:function(){
				delGraph();
			}
		}]
	});

}


/**
 * 展现添加图形窗口
 */
function showAddInfo(){
	$("#editGraphTable").show();
	$('#editGraphForm').form('clear');
	
	$('#applyBtn').hide();// 默认屏蔽
	
	$("#editDlgBtn").show();
	$('#editDlg').window({
		title:' 添加图形',
		iconCls:'icon-add',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#editDlg').window('move',{top:20,left:20});
	$('#editDlg').window('open');
}
/**
 * 展现编辑图形窗口
 */
function showEditInfo(id){
	$("#editGraphTable").show();
	$('#editGraphForm').form('clear');
	$('#applyBtn').hide();// 默认屏蔽
	$("#graphId").val(id);
	
	//$("#editGraphForm").attr("src",appPath + "/itbGraph/getGraphData.action?graph_id="+ id);
	var url = appPath + "/itbGraph/getGraphData.action?graph_id="+ id;
	$.get(url,function(data){
		if (data && data.length>0){
			var info = data[0];
//			$("#graphName").val(info.graph_name);
//			$("#graphType").val(info.graph_type);
			
			var showData = '{"type":'+info.graph_type+
							',"name":"'+info.graph_name+'"'+
							',"data":'+info.data+'}';
			$("#graphData").val(showData);
		}
	});
	
	$("#editDlgBtn").show();
	$('#editDlg').window({
		title:' 编辑图形',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#editDlg').window('move',{top:20,left:20});
	$('#editDlg').window('open');
	
}

/**
 * 刷新预览
 */
function refreshThumb(){
	var selectItem=$("#graphGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择图形','warning');
		return;
	}
	$.messager.confirm("确认", "是否确认刷新缩略图", function (r) {  
        if (r) {
        	$.loading(true);
        	// 生成缩略图
			var url = getImageServer()+'/image/createGraphThumb';
			var ids = "";
			$.each(selectItem, function(index, item){
				ids = ids + item.graph_id + ",";
			});
			if (ids.length>1){
				ids = ids.substring(0, ids.length-1);
			}
		    var sendData = {
		    	userId:g_userId,
		        ids:ids
		    };
		    $.post(url, sendData, function(ret){
		    	$.loading(false);
		        if (ret.success == 1) {
		        	$.messager.alert('提示信息','生成预览图成功！','info');
					doQuery();
		        } else {
		        	$.messager.alert('提示信息','生成预览图失败！','info');
		        }
		    });
        }
	});
}

/**
 * 删除图形
 */
function delGraph(){
	var selectItem=$("#graphGrid").datagrid("getChecked");
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择图形','warning');
		return;
	}
	$.messager.confirm("确认", "是否确认删除", function (r) {  
        if (r) { 
			var ids = "";
			$.each(selectItem, function(index, item){
				ids = ids + item.graph_id + ",";
			});
			var url = appPath+"/itbGraphWeb/deleteGraph.action?delIds="+ids;
			$.post(url,function(data){
				if(data=="ok"){
					$.messager.alert('提示信息','删除成功','info');
					doQuery();
				}
			});
        }
	});
}

/**
 * 检测录入数据
 */
function chkHelp(){
	window.open("http://json.cn/#");
}

// graphData:{type:xxx, name:yyy, data:zzz}
function chkGraphData(graphData){
	if ( !graphData || 
			!graphData.hasOwnProperty("type") ||
			!graphData.hasOwnProperty("name") ||
			!graphData.hasOwnProperty("data") ) {
		return false;
	}
	return true;
}

// 获取处理用图形数据
function getGraphData(){
//	var name = $("#graphName").val();
//	var type = $("#graphType").val();
	var graphData = $("#graphData").val();
	var graphId = $("#graphId").val() || "-1";
	
//	var inputType = "0";
//	if ($("#inputType").prop('checked')) {
//		inputType = "1";
//	}
//	
//	if ((!name)||(name.length<=0)) return $.messager.alert('提示信息','请输入图形名称！','info');
	if ((!graphData)||(graphData.length<=0)) {
		$.messager.alert('提示信息','请录入图形数据！','info');
		return null;
	}
	
	try {
		var inputData = [];
		var inputJsonData = JSON.parse(graphData);
		if (Array.isArray(inputJsonData) && inputJsonData.length>0) {
			// 批量录入
			for (var i in inputJsonData){
				var item = inputJsonData[i];
				if (!chkGraphData(item)){
					$.messager.alert('提示信息','图形数据格式错误！','info');
					return null;
				}
				
				var dto = {
						"graph_id": graphId,
						"graph_name": item.name,
						"graph_type": item.type,
						"data": JSON.stringify(item.data)
				};
				inputData.push(dto);
				
				if (graphId && graphId.length>0 && Number(graphId)>=0) {
					break;// 更新的场合，只取第一个图形信息
				}
			}
			
		} else {
			// 单个录入
			if (!chkGraphData(inputJsonData)){
				$.messager.alert('提示信息','图形数据格式错误！','info');
				return null;
			}
			var dto = {
					"graph_id": graphId,
					"graph_name": inputJsonData.name,
					"graph_type": inputJsonData.type,
					"data": JSON.stringify(inputJsonData.data)
			};
			inputData.push(dto);
		}
		
		return inputData;
		
	} catch(err) {
		$.messager.alert('提示信息','图形数据格式错误！','info');
		return null;
	}
}

// 预览实际图形
function doPreview(){
	var arrGraphData = getGraphData();
	if(arrGraphData){
		localStorage.removeItem("_itb_tmp_graph_");
		localStorage.setItem("_itb_tmp_graph_",JSON.stringify(arrGraphData));
		var egretUrl = appPath+"/js/egret_s/index.html";
		window.open(egretUrl);
		$('#applyBtn').show();// 放开确认按钮
	}
}

/**
 * 开始上传图形
 */
function doPostData(){
	var arrGraphData = getGraphData();
	if(arrGraphData){
		$.messager.confirm("确认", "是否确认提交图形数据？<br><span style='color:red'>*请确保已经过预览检查</span>", function (r) {  
	        if (r) {
	        	// 后台登录
	    		var url = appPath+"/itbGraphWeb/addGraph.action";
	    		var sendData = {
//	    			"graphInfo.graph_id": $("#graphId").val(),
//	    			"graphInfo.graph_name": name,
//	    			"graphInfo.graph_type": type,
//	    			"graphInfo.data": data,
	    			"inputData": JSON.stringify(arrGraphData)
	    		};
	    	    $.post(url, sendData, function(data){  
	    			if (data && data.retIds && data.retIds.length>0) {
	    				// 生成缩略图
	    				var postUrl = 'http://120.27.141.154:3003/image/createGraphThumb';
	    				var ids = "";
	    				for (var n in data.retIds){
	    					ids = ids + data.retIds[n] + ',';
	    				}
	    				if (ids.length>1){
	    					ids = ids.substring(0, ids.length-1);
	    				}
	    			    var sendData = {
	    			    	userId:g_userId,
	    			        ids:ids
	    			    };
	    			    $.post(postUrl, sendData, function(ret){
	    			        if (ret.success == 1) {
	    			        	$.messager.alert('提示信息','提交成功','info');
	    						doQuery();
	    			        } else {
	    			        	$.messager.alert('提示信息','生成预览图失败！','info');
	    			        }
	    			    });
	    	        } else {
	    	        	$.messager.alert('提示信息','提交失败','info');
	    	        } 
	    	    });
	        }
		});// confirm
	}// not null
}

/**
 * 关闭对话框
 */
function cancelPostData(){
	$('#editDlg').window('close');
}

/**
 * 获取请求信息
 */
function getQueryParam(){
	var queryObject = {};
	var findName=$("#queryGraphName").val();
	if(findName&&findName.length>0) queryObject.findName = findName;
	return queryObject;
}

/**
 * 查询数据
 */
function doQuery(){
	$("#graphGrid").datagrid('unselectAll');
	$("#graphGrid").datagrid('load',getQueryParam());
}

function onInputTypeClick(){
//	if($("#inputType").prop('checked')){// 批量录入
//		$("#graphName").attr("disabled","disabled");
//		$("#graphType").attr("disabled","disabled");
//	}else{
//		$("#graphName").removeAttr("disabled");
//		$("#graphType").removeAttr("disabled");
//	}
}

function fmtCreateTime(value, rowData, rowIndex){
	if(!value)return "";
	var s = new Date(value);
	return rowData.create_time=$.DateUtil.format(s,'yyyy/MM/dd hh:mm:ss');
}

function fmtHotFlag(value, rowData, rowIndex){
	if(rowData.hotFlag==1)return "是";
	return "否";
}
